let deviceId,serviceId,characteristicId,discoveryStarted;

let REQdata=[];
let chs=[];
let that='';
let  isAUTO=false;
const app = getApp();
function inArray(arr, key, val) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i][key] === val) {
      return i;
    }
  }
  return -1;
}
// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
  var hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join('');
}
// 字符串转byte
function stringToBytes(str) {
  var array = new Uint8Array(str.length);
  for (var i = 0, l = str.length; i < l; i++) {
    array[i] = str.charCodeAt(i);
  }
  console.log(array);
  return array.buffer;
}
/**
   * 向设备写入命令
   */
function writeBLECharacteristicValue(command) {
  if(command=='AUTO_ACC'){
    isAUTO=true
  }
  let deviceId=wx.getStorageSync('DeviceId');
  let serviceId=wx.getStorageSync('ServiceId');
  let characteristicId=wx.getStorageSync('CharacteristicId');
  // var that = this;
  /*
    对应命令转为16进制的形式
    START   = [83, 84, 65, 82, 84]+时间戳
    STOP    = [83, 84, 79, 80]
    REQDATA = [82, 69, 81, 68, 65, 84, 65]
  */
  var buffer = stringToBytes(command)
  let isSTART = command.indexOf('START');//是否包含'START'指令；
  console.log('发送参数',
    {
      'deviceId': deviceId,
      'serviceId': serviceId,
      'characteristicId': characteristicId,
      'value': buffer
    })
  wx.writeBLECharacteristicValue({
    deviceId: deviceId,
    serviceId: serviceId,
    characteristicId: characteristicId,
    value: buffer,
    success: function (res) {
      //同步指令；
      if (command === "REQDATA") {
        wx.showLoading({
          title: '正在同步数据...',
        });

        console.log("同步成功", res)
      } else if (isSTART != -1) {
        console.log("发送成功start", res);
      }
    },
    fail(res) {
      console.log("发送失败", res)
    }
  })
};
//附近的蓝牙外围设备

//监听寻找到新设备的事件
function onBluetoothDeviceFound() {

  wx.onBluetoothDeviceFound(
    {
        success: (res) => {
            res.devices.forEach(device => {
                let devices=[];
                 let IsBICQ = device.name.indexOf('BICQ') != -1;
                 if (!device.name && !device.localName) {
                   return
                 }
                 if (IsBICQ) {
                   const foundDevices = devices;
                   const idx = inArray(foundDevices, 'deviceId', device.deviceId)
                   const data = {}
                   if (idx === -1) {
                     devices[foundDevices.length] = device
                   } else {
                     devices[idx] = device
                   };
                   that.setData({
                     devices:devices
                   });
                 };
               })
        },
        fail(res) {
          console.log('onBluetoothDeviceFound fail', res)
        }
  })
};
function startBluetoothDevicesDiscovery() {
    // if (discoveryStarted) {
    //   return
    // }
    // discoveryStarted = true
    wx.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: true,
      success: (res) => {
        console.log('startBluetoothDevicesDiscovery success', res)
        onBluetoothDeviceFound()
      },
      fail(res) {
        console.log('startBluetoothDevicesDiscovery fail', res)
      }
    })
  };
/**
 * 创建连接方法
 */
function createBLEConnection(e) {
  const ds = e.currentTarget.dataset;
  const deviceId = ds.deviceId;
  const name = ds.name;
  wx.setStorageSync('DeviceId', ds.deviceId);
  wx.setStorageSync('Name', ds.name);
  console.log('连接设备：', ds)
  wx.createBLEConnection({
    deviceId,
    success: (res) => {
      console.log('连接成功', res);
      getBLEDeviceServices(deviceId);
      wx.setStorageSync('IsConnect', true);
     that.setData({
          showConnect: false,
          showTips:true,
        })
    }
  })
};

/**
 * 连接成功之后解析该设备中的服务
 */
function getBLEDeviceServices(deviceId) {
  wx.getBLEDeviceServices({
    deviceId,
    success: (res) => {
      console.log('分析服务码', res)
      for (let i = 0; i < res.services.length; i++) {
        // 注：解析过程出现两个service，第二个是以前使用的，所以这里添加判断
        if (res.services[i].uuid.indexOf("6E400001") != -1) {
          if (res.services[i].isPrimary) {
            wx.setStorageSync('ServiceId', res.services[i].uuid);
            getBLEDeviceCharacteristics(deviceId, res.services[i].uuid);
            return
          }
        }
      };
    },
    fail(res) {
      console.log('获取服务码错误：', res)
    }
  });
};
/**
 * 获取到我们需要的服务之后解析服务中的write和notify服务
 */
function getBLEDeviceCharacteristics(deviceId, serviceId) {
  var that = this;
  wx.getBLEDeviceCharacteristics({
    deviceId,
    serviceId,
    success: (res) => {
      console.log('getBLEDeviceCharacteristics success', res.characteristics)
      for (let i = 0; i < res.characteristics.length; i++) {
        let item = res.characteristics[i]
        if (item.properties.read) {
          wx.readBLECharacteristicValue({
            deviceId,
            serviceId,
            characteristicId: item.uuid,
          })
        }
        if (item.properties.write) {
          deviceId = deviceId;
          serviceId = serviceId;
          characteristicId = item.uuid;
          wx.setStorageSync('DeviceId',deviceId);
          wx.setStorageSync('ServiceId',serviceId);
          wx.setStorageSync('CharacteristicId',item.uuid);
          
          startConnect();
        }
        if (item.properties.notify || item.properties.indicate) {
          wx.notifyBLECharacteristicValueChange({
            deviceId,
            serviceId,
            characteristicId: item.uuid,
            state: true,
          })
        }
      }
    },
    fail(res) {
      console.error('getBLEDeviceCharacteristics', res)
    }
  });
  /**
   *  操作之前先监听，保证第一时间获取数据，即先注册notify服务，随时监听着
   */
  wx.onBLECharacteristicValueChange((characteristic) => {
    const idx = inArray(chs, 'uuid', characteristic.characteristicId);
    REQdata.push(ab2hex(characteristic.value));
    console.log('监听同步返回数据', ab2hex(characteristic));
    console.log('同步单个数据', ab2hex(characteristic.value));
    console.log('同步数据数组参数', REQdata);
    if (characteristic.value.byteLength == 3) {
      wx.hideLoading();
      wx.request({
        url: 'http://114.215.78.47:8005/handRing/updataDTing', //仅为示例，并非真实的接口地址
        data: {
          handRingMac: deviceId,
          DataStreams: REQdata
        },
        method: 'POST',
        header: {
          'content-type': 'application/json' // 默认值
        },
        success: function (res) {
          console.log(res.data);
        },
        fail: (res) => {
          console.log(res.data);
        },
      })
      console.log({
        handRingMac: deviceId,
        DataStreams: REQdata
      })
      return;
    }

  });

};
/**
 * 打开蓝牙适配器
 */
function openBluetoothAdapter(e) {
  that=e
  wx.openBluetoothAdapter({
    success: (res) => {
      console.log('openBluetoothAdapter success', res)
      startBluetoothDevicesDiscovery()
    },
    fail: (res) => {
      if (res.errCode === 10001) {
        wx.onBluetoothAdapterStateChange(function (res) {
          console.log('onBluetoothAdapterStateChange', res)
          if (res.available) {
            startBluetoothDevicesDiscovery()
          }
        })
      } else {
        wx.showModal({
          title: '提示',
          content: '请开启蓝牙设备',
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定')
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
        console.log('onBluetoothAdapterStateChange fail', res)
      }
    }
  })
};

function startConnect() {
  let d = Date.parse(new Date()) / 1000;
  let parameter = "START" + d;
  writeBLECharacteristicValue(parameter);
};


module.exports = {
  openBluetoothAdapter,//蓝牙设备状态
  createBLEConnection,//连接设备；
  upload,//同步数据；
//   writeBLECharacteristicValue//同步

}
